package com.netty.demo.server.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * websocket服务
 *
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年10月31日  10:36 </p>
 * <p>address: 四川成都 </p>
 */
@Slf4j
@Component
public class NettyWebsocketServer {
    private final NioEventLoopGroup boss = new NioEventLoopGroup(1);
    private final NioEventLoopGroup work = new NioEventLoopGroup();
    @Resource
    private NettyWebsocketServerInitializer nettyWebsocketServerInitializer;

    public void start() {
        log.info("正在启动websocket服务器");
        try {
            //创建ServerBootstrap实例
            ServerBootstrap bootstrap = new ServerBootstrap();
            //初始化ServerBootstrap的线程组
            bootstrap.group(boss, work);
            //设置将要被实例化的ServerChannel类
            bootstrap.channel(NioServerSocketChannel.class);
            //开启广播
            bootstrap.option(ChannelOption.SO_BROADCAST, true);
            //重复地址
            bootstrap.option(ChannelOption.SO_REUSEADDR, true);
            // 是否启用心跳保活机机制
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

            bootstrap.childHandler(nettyWebsocketServerInitializer);
            Channel channel = bootstrap.bind(8081).sync().channel();
            log.info("webSocket服务器启动成功：" + channel);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("运行出错：" + e);
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
            log.info("websocket服务器已关闭");
        }
    }

    @PreDestroy
    public void destroy() {
        work.shutdownGracefully();
        boss.shutdownGracefully();
    }
}
